package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
  "fmt"
  "github.com/golang/protobuf/ptypes"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"io/ioutil"
	"log"
	"strtv.cn/ad-service/bootstrap/config"
	"strtv.cn/ad-service/cmd/client-grpc/auth"
	v1 "strtv.cn/ad-service/pkg/api/v1"
	"time"
)

func main() {
  c, err := GetClientCredentials()
  if err != nil {
    log.Fatalf("credentials err: %v", err)
  }
  //构建Token
  token := auth.Token{
    Value: "bearer ad.service.token",
  }
  host := config.String("SERVICE.ADDR")
  port := config.String("SERVICE.GRPCPORT")
  conn, err := grpc.Dial(host+":"+port, grpc.WithTransportCredentials(c), grpc.WithPerRPCCredentials(&token))
  if err != nil {
    log.Fatalf("grpc.Dial err: %v", err)
  }
  defer conn.Close()
  client := v1.NewDepartmentServiceClient(conn)
  // create department

  createdAt, err := ptypes.TimestampProto(time.Now())
  if err != nil {
    log.Fatalf("部门createdAt 格式不正确 err: %v", err)
  }

  department := v1.Department{
    Name:        "新闻节目中心",
    Description: "新闻节目中心",
    Pid:         1,
    Status:      true,
    CreatedAt:   createdAt,
    UpdatedAt:   createdAt,
  }
  resp, err := client.Create(context.Background(), &v1.CreateRequest{
    Api:        "v1",
    Department: &department,
  })
  if err != nil {
    log.Fatalf("新建部门失败 err: %v", err)
  }
  log.Printf("新建部门成功ID为: %d", resp.Id)

  // get department by id
  /*
  	resp, err := client.Read(context.Background(), &v1.ReadRequest{
  		Api: "v1",
  		Id: 3,
  	})
  	if err != nil {
  		log.Fatalf("获取部门失败 err: %v", err)
  	}

  	createdAt, err := ptypes.Timestamp(resp.Department.CreatedAt)
  	if err != nil {
  		log.Fatalf("部门createdAt 格式不正确 err: %v", err)
  	}

  	updatedAt, err := ptypes.Timestamp(resp.Department.UpdatedAt)
  	if err != nil {
  		log.Fatalf("updatedAt 格式不正确 err: %v", err)
  	}

  	log.Printf("获取部门成功ID为: %d:%d:%s:%v:%s:%s:%s", resp.Department.Id, resp.Department.Pid, resp.Department.Name, resp.Department.Status, resp.Department.Description, createdAt, updatedAt)
  */
  // update department
  /*
  	updateAt, err := ptypes.TimestampProto(time.Now())
  	if err != nil {
  		log.Fatalf("部门 updateAt 格式不正确 err: %v", err)
  	}
  	department := v1.Department{
  		Id:          2,
  		Name:        "办公室",
  		Description: "办公室",
  		Pid:         1,
  		Status:      true,
  		//CreatedAt: createdAt,
  		UpdatedAt: updateAt,
  	}
  	resp, err := client.Update(context.Background(), &v1.UpdateRequest{
  		Api:        "v1",
  		Department: &department,
  	})
  	if err != nil {
  		log.Fatalf("更新部门失败 err: %v", err)
  	}
  	log.Printf("更新部门影响的记录数: %d", resp.Updated)
  */
  // delete department
  /*
  	  resp, err := client.Delete(context.Background(), &v1.DeleteRequest{
  			Api:        "v1",
  			Id:         2,
  		})
  		if err != nil {
  			log.Fatalf("删除部门失败 err: %v", err)
  		}
  		log.Printf("删除部门影响的记录数: %d", resp.Deleted)
  */
  // get all department
  /*
  	resp, err := client.ReadAll(context.Background(), &v1.ReadAllRequest{
  		Api: "v1",
  	})
  	if err != nil {
  		log.Fatalf("获取部门失败 err: %v", err)
  	}
  	for index, value := range resp.Departments {
  		createdAt, err := ptypes.Timestamp(value.CreatedAt)
  		if err != nil {
  			log.Fatalf("部门createdAt 格式不正确 err: %v", err)
  		}

  		updatedAt, err := ptypes.Timestamp(value.UpdatedAt)
  		if err != nil {
  			log.Fatalf("updatedAt 格式不正确 err: %v", err)
  		}
  		log.Printf("新建部门列表: { %d:  %d : %s : %s : %d : %v : %s : %s }", index, value.Id, value.Name, value.Description, value.Pid, value.Status, createdAt, updatedAt)

  	}
  */
}

func GetClientCredentials() (credentials.TransportCredentials, error) {
  cert, err := tls.LoadX509KeyPair("../../tls/client/client.pem", "../../tls/client/client.key")
  if err != nil {
    return nil, fmt.Errorf("tls.LoadX509KeyPair err: %v", err)
  }

  certPool := x509.NewCertPool()
  ca, err := ioutil.ReadFile("../../tls/ca.pem")
  if err != nil {
    return nil, fmt.Errorf("ioutil.ReadFile err: %v", err)
  }

  if ok := certPool.AppendCertsFromPEM(ca); !ok {
    return nil, fmt.Errorf("certPool.AppendCertsFromPEM err")
  }

  c := credentials.NewTLS(&tls.Config{
    Certificates: []tls.Certificate{cert},
    ServerName:   config.String("SERVICE.COMMONNAME"),
    RootCAs:      certPool,
  })
  return c, err
}
